<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>doc view</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
</head>

<body>
    <div id="webConsole"><textarea readonly="readonly"></textarea></div>
    <div id="viewMain">
        <div id="viewBody" class="container img-noborder-body"></div>
        <div id="loadPromt" class="view-loading">
            <img id="view-loading-img" class="view-loading-img" src="img/loading.gif">
            <div id="view-loading-retry" class="view-loading-retry">
                <div class="loading-retry-text"></div>
                <div class="loading-retry-button" data-i18n="retry"></div>
            </div>
        </div>
        <div class="footer text-muted" data-i18n="notice"></div>
    </div>
    <script src="js/jquery-3.3.1.min.js"></script>
    <script src="js/jquery.i18n.js"></script>
    <script src="js/jquery.i18n.messagestore.js"></script>
    <script src="js/main.js"></script>
    <script>
        (function ($) {
          var logger = $.logger

          var localUrlData = {}
          var authAllowed = false
          var pageDataReady = false
          var win = $(window)
          var baseUrl

          var isInitPages = false
          var totalPages = 0
          var loadingImg = 'img/loading.gif'

          $(function () {
            $('#viewMain').i18n()

            initJSAPI()

            win.on('resize', function (e) {
              $('.img-container').css('min-height', $('#img_page_1').height() + 30)
            })

            $.SDK.jsComplete()
          })

          function initJSAPI () {
            window.view = function (docViewUrl, sysCode, viewInfo, localCache) {
              logger.debug('SDK -> view(' + docViewUrl + ',' + sysCode + ',' + viewInfo + ',' + localCache + ')')
              baseUrl = docViewUrl
              $.initDocView(docViewUrl, sysCode, viewInfo)
              if (localCache) {
                var pageUrls = JSON.parse(localCache)
                if (typeof pageUrls === 'object') {
                  if (pageUrls.totalPages > 0 && typeof pageUrls.pages === 'object') {
                    localUrlData = pageUrls.pages
                    totalPages = pageUrls.totalPages
                    var pages = ''
                    for (var p in localUrlData) {
                      pages += ',' + p
                    }
                    logger.debug('本地缓存解析成功，totalPages:' + totalPages + '，pages:' + pages.substr(1))
                    initAllBlankPage()
                    isInitPages = true
                  }
                }
              }
              appendImg()
              return '1'
    }

            window.authResult = function (code) {
              $.logger.debug('SDK -> authResult(' + code + ')')
              switch (code) {
                case '100':
                  authSuccess()
                  break
                case '101':
                  showRefuse(code)
                  break
                case '102':
                case '103':
                  showAuthRetry(code)
                  break
                default:
                  break
              }
              return '1'
    }

            window.cacheImgCallback = function (page, chunk, result, cacheUrl) {
              logger.debug('SDK -> cacheImgCallback(' + page + ',' + chunk + ',' + result + ',' + cacheUrl + ')')
              localUrlData[page.toString()] = cacheUrl
              return '1'
    }
          }

          var authSuccess = function () {
            $.logger.debug('已授权')
            authAllowed = true
            showView()
            authSuccess = showRefuse = showAuthRetry = $.noop
          }

          function showView () {
            if (!authAllowed || !pageDataReady) return
            $('#viewBody').show()
            $('.footer').show()
            $('#loadPromt').hide()
          }

          var showRefuse = function (code) {
            $.logger.debug('未授权')
            $('#viewBody').empty()
            $.throwError(code, null)
            authSuccess = showRefuse = showAuthRetry = $.noop
          }

          var showAuthRetry = function (code) {
            $.logger.debug('鉴权失败' + code)
            $.throwError(code, $.SDK.authRetry)
          }

          function appendImg () {
            var page = 1
            // 先从本地寻找图片
            var img = $('#img_page_' + page)
            if (!img.data('loaded') && !!localUrlData[page.toString()]) {
              logger.debug('从本地缓存加载页：' + page)
              img.data('from', 'local').attr('src', localUrlData[page.toString()]).data('loaded', true)
              pageDataReady = true
              showView()
              return
    }

            logger.debug('开始远程加载：' + page)
            $.remoteLoad({
              starPage: page,
              startPage: page,
              endPage: page
            }, function (json) {
              logger.debug('远程调用成功响应[' + page + ']：' + JSON.stringify(json))
              if (!json.error && !!json.data && json.data.TotalPages > 0) {
                totalPages = json.data.TotalPages
                if (!isInitPages) {
                  initAllBlankPage()
                  isInitPages = true
                }
                $.each(json.data.Urls, function (i, o) {
                  var img = $('#img_page_' + o.Index)
                  if (!img.data('loaded')) {
                    logger.debug('从远程加载页：' + o.Index)
                    img.data('from', 'remote').attr('crossOrigin', 'Anonymous').attr('src', baseUrl + o.Url).data('loaded', true)
                  }
                })
                // 记录请求成功的页数
                pageDataReady = true
                showView()
              } else {
                var errorCode
                if (json.code === 200) {
                  // 由转换服务返回的错误
                  switch (json.error.code) {
                    case 'DOWNLOAD_FAILED':
                      errorCode = '510'
                      break
                    case 'FILE_SIZE_OUT_OF_LIMIT':
                      errorCode = '511'
                      break
                    default:
                      errorCode = '502'
                      break
                  }
                } else {
                  // api返回的错误
                  errorCode = json.code.toString()
                }
                $.throwError(errorCode, function () {
                  logger.debug('重试appendImg：' + page)
                  appendImg()
                })
              }
            }, function (XMLHttpRequest, textStatus, errorThrown) {
              logger.error('请求失败[' + page + '-' + page + ']：textStatus=' + textStatus + ',errorThrown=' + errorThrown)
              var errorCode = '400'
              if (textStatus === 'timeout') {
                errorCode = '504'
              }
              $.throwError(errorCode, function () {
                logger.debug('重试appendImg：' + page)
                appendImg()
              })
            })
          }

          function initAllBlankPage () {
            var imgDom = ''
            for (var i = 1; i <= totalPages; i++) {
              imgDom += '<div id="img_con_' + i + '" class="img-container" data-page="' + i + '">' +
                        '<img id="img_page_' + i + '" class="img-content">' +
                        '<img id="img_loading_' + i + '" class="img-loading" src="' + loadingImg + '">' +
                        '</div>'
            }
            $('#viewBody').append(imgDom)

            // 图片加载完成后隐藏loading，抽取流本地缓存
            $('.img-content').on('load', function () {
              var img = $(this)
              img.data('success', true).next().remove()
              if (!img.data('hd') && !!img.data('from') && img.data('from') === 'remote') {
                var base64Data = $.getImgBase64(this)
                localUrlData[img.parent().data('page').toString()] = base64Data
                $.SDK.cacheImg(totalPages, img.parent().data('page'), base64Data)
              }
            }).on('error', function () {
              var img = $(this)
              img.removeData('loaded')
              logger.error('图片加载失败[1]')
              if (img.data('from') === 'local') {
                // 如果加载失败的图片来自本地缓存就清除掉本地缓存
                delete localUrlData['1']
              }
              $.throwError('400', function () {
                logger.debug('重试appendImg：1')
                appendImg()
              })
            })
          }
        })(window.jQuery)
    </script>
</body>

</html>